package com.springboot.frame.starter.web.csrf;


import com.springboot.frame.web.csrf.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Csrf 的spring-boot启动器
 *
 * @author TaoYu MaYing
 */
@Configuration
@EnableConfigurationProperties(CsrfProperties.class)
@ConditionalOnProperty({"web.csrf.enabled"})
public class CsrfAutoConfiguration {

  /**
   * csrf配置参数
   */
  private final CsrfProperties properties;

  public CsrfAutoConfiguration(CsrfProperties properties) {
    this.properties = properties;
  }

  @Bean
  public FilterRegistrationBean csrfFilterRegistrationBean(CsrfTokenRepository csrfTokenRepository,
                                                           CsrfMatcher csrfMatcher,
                                                           CsrfProcessor csrfProcessor) {
    CsrfFilter csrfFilter = new CsrfFilter(csrfTokenRepository, csrfMatcher, csrfProcessor);
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(csrfFilter);
    Integer order = properties.getOrder();
    filterRegistrationBean.setOrder(order);
    return filterRegistrationBean;
  }

  @Bean
  @ConditionalOnMissingBean
  public CsrfMatcher csrfMatcher() {
    return new MethodCsrfMatcher();
  }

  @Bean
  @ConditionalOnMissingBean
  public CsrfTokenRepository csrfTokenRepository() {
    return new SessionCsrfTokenRepository();
  }

  @Bean
  @ConditionalOnMissingBean
  public CsrfProcessor filterDeniedHandler() {
    return new DefaultCsrfProcessor();
  }

}
